package com.itheima.controller;


import com.github.pagehelper.PageInfo;
import com.itheima.entity.Category;
import com.itheima.result.Result;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询
     *
     * @param pageNum  当前页码
     * @param pageSize 每页大小
     * @return PageInfo<Movies>
     */
    @GetMapping("list")
    public Result findByPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize,
            String categoryName) {
        //调用service完成分页查询
        PageInfo<Category> list = categoryService.findByPage(pageNum, pageSize, categoryName);
        return Result.success(list);
    }

    /**
     * 根据id查询
     *
     * @param id 主键
     * @return movies
     */
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        Category category = categoryService.findById(id);
        return Result.success(category);
    }

    /**
     * 新增或修改
     *
     * @param
     * @return 无
     */
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody Category category) {
        Integer id = category.getId();
        Category categoryById = categoryService.findById(id);

        if (categoryById == null) {
            // 新增
            categoryService.save(category);
        } else {
            // 修改
            categoryService.update(category);
        }
        return Result.success();
    }

    /**
     * 根据id删除
     *
     * @param id 主键
     * @return 无
     */
    @DeleteMapping("/deleteById")
    public Result deleteById(@RequestParam Integer id) {
        categoryService.deleteById(id);
        return Result.success();
    }

    /**
     * 批量删除
     *
     * @param ids 主键或主键数组
     * @return 无
     */
    @DeleteMapping("/deleteByIds")
    public Result deleteByIds(@RequestParam List<Integer> ids) {
        categoryService.deleteBatch(ids);
        return Result.success();
    }

}